﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Shell;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell.Interop;
using TFDP.VsPackage.Services;
using System.Diagnostics;
using System.ComponentModel.Composition;
using EnvDTE80;

namespace TFDP.VsPackage.Forms
{
    [Guid(QueueMonitor.guidString)]
    public class QueueMonitor : ToolWindowPane
    {
        public const string guidString = "AEDF9A31-79D9-4833-B197-A611CC3A94EF";
        public static Guid ToolWindowGuid = new Guid("{" + guidString + "}");

        private QueueMonitorContent qmContent;
        private IProjectNotifierService qmService;

        public QueueMonitor()
            : this(null)
        {
        }

        public QueueMonitor(IServiceProvider provider)
            : base(provider)
        {
            qmContent = new QueueMonitorContent();
            
            BitmapResourceID = 302;
            BitmapIndex = 0;

            this.Content = qmContent;
        }

        public override void OnToolWindowCreated()
        {
            base.OnToolWindowCreated();

            this.Caption = "Queue Monitor";

            this.qmService = ((IServiceProvider)this.Package).GetService(typeof(ProjectNotifierService)) as IProjectNotifierService;

            if (this.qmService != null)
            {
                this.qmService.QueueChanged += new EventHandler<QueueChangedEventArgs>(qmService_QueueChanged);
                this.qmService.ProjectClosed += new EventHandler<ProjectClosedEventArgs>(qmService_ProjectClosed);

                var processors = this.qmService.QueryProcessors();
                processors
                    .ToList()
                    .ForEach(p => this.qmContent.QueueChanged(p));
            }
            else
                Trace.WriteLine("QueueMonitor: Unable to obtain QueueNotifierService");            
        }

        protected override void OnClose()
        {
            this.qmService.QueueChanged -= new EventHandler<QueueChangedEventArgs>(qmService_QueueChanged);
            this.qmService.ProjectClosed -= new EventHandler<ProjectClosedEventArgs>(qmService_ProjectClosed);

            base.OnClose();
        }

        private void qmService_QueueChanged(object sender, QueueChangedEventArgs e)
        {
            if (e.Processor == null)
                return;

            this.qmContent.QueueChanged(e.Processor);
        }

        private void qmService_ProjectClosed(object sender, ProjectClosedEventArgs e)
        {
            if (e.Processor == null)
                return;

            this.qmContent.ProjectClosed(e.Processor);
        }
    }
}
